package com.dragon.service.impl;

import cn.hutool.core.io.FileUtil;
import com.dragon.mapper.UserMapper;
import com.dragon.pojo.User.*;
import com.dragon.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    // 头像文件实际路径
    @Value("${file.storage.avatar-path}")
    private String avatarPath;


    @Override
    public User login(LoginInfo loginInfo) {
        if(!loginInfo.getIdentifier().contains("@")){
            return userMapper.loginForUserName(loginInfo);
        } else {
            return userMapper.loginForEmail(loginInfo);
        }
    }

    @Override
    public void register(User user) {
        user.setIsCodePublic(0);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.register(user);
    }

    @Override
    public UserInfo getUserInfo(User user) {
        return userMapper.getUserInfo(user);
    }

    @Override
    public void updateUserInfo(User user) {
        userMapper.updateUserInfo(user);
    }

    @Override
    public void updatePwd(User user) {
        userMapper.updatePassword(user);
    }

    @Override
    public String getPassword(User user) {
        return userMapper.getPasswordForId(user);
    }

    @Override
    public void logout(User user) {
        userMapper.logout(user);
    }

    @Override
    public String updateAvatar(User user, MultipartFile avatar) throws IOException {
        // 使用UUID生成文件名
        String fileName = UUID.randomUUID() + ".jpg";
        String absolutePath = avatarPath + fileName;

        // 删除原文件
        User getAvatarUser = userMapper.getAvatarById(user);
        if(getAvatarUser != null){
            FileUtil.del(avatarPath + getAvatarUser.getAvatar());
        }
        // 保存文件到目录
        avatar.transferTo(new File(absolutePath));
        // 保存文件名到数据库
        user.setAvatar(fileName);
        userMapper.updateAvatar(user);

        return fileName;
    }

    @Override
    public UserListResult getUserList(UserSelectInfo info) {
        info.setOffset((info.getPageNumber()-1)*info.getListNumber());

        List<UserList> userList = userMapper.getUserList(info);

        return new UserListResult(userList, userMapper.getUserTotal(info));
    }

}
